﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Ordinapoche.WinForms
{
    public partial class MemoryControl : UserControl
    {
        private Memory _Memory;
        public MemoryControl ()
        {
            InitializeComponent ();
        }

        private void Attach (Memory aMemory)
        {
            aMemory.DataChanged += new EventHandler<MemoryChangeEventArgs> (aMemory_DataChanged);
            ReloadMemory ();
        }

        private void Detach (Memory aMemory)
        {
            aMemory.DataChanged -= new EventHandler<MemoryChangeEventArgs> (aMemory_DataChanged);
            ReloadMemory ();
        }

        public Memory Memory
        {
            get
            {
                return _Memory;
            }
            set
            {
                if (value != _Memory)
                {
                    if (_Memory != null)
                    {
                        Detach (_Memory);
                    }
                    _Memory = value;
                    if (_Memory != null)
                    {
                        Attach (_Memory);
                    }
                }
            }
        }

        private string TextForCell (int i)
        {
            if (_Memory == null)
            {
                return String.Format ("{0:02}: ---", i);
            }
            else
            {
                return String.Format ("{0:D2}: {1:D3}", i, _Memory[i]);
            }
        }

        private void ReloadMemory ()
        {
            list_Memory.Items.Clear ();

            for (int i = 0; i < 100; i++)
            {
                var itm = list_Memory.Items.Add (TextForCell(i));
            }
        }

        private void aMemory_DataChanged (object sender, MemoryChangeEventArgs e)
        {
            list_Memory.Items[e.Cell].Text = TextForCell (e.Cell);
        }
 
        void listView1_SelectedIndexChanged (object sender, EventArgs e)
        {

        }
    }
}
